package com.trie;

import java.util.HashMap;
import java.util.Map;

/**
 * 动态字典树，无大小限制，效率相对于静态字典树要慢
 * @author `RKC`
 * @date 2021/11/18 10:23
 */
public class DynamicTrie {

    private final TrieNode root = new TrieNode(' ');

    public void insert(String word) {
        TrieNode cur = root;
        for (int i = 0; i < word.length(); i++) {
            if (!cur.childNodes.containsKey(word.charAt(i))) {
                TrieNode trieNode = new TrieNode(word.charAt(i));
                cur.childNodes.put(word.charAt(i), trieNode);
            }
            cur = cur.childNodes.get(word.charAt(i));
        }
        cur.isWord = true;
    }

    public boolean exists(String word) {
        TrieNode cur = root;
        for (int i = 0; i < word.length(); i++) {
            if (!cur.childNodes.containsKey(word.charAt(i))) return false;
            cur = cur.childNodes.get(word.charAt(i));
        }
        return cur.isWord;
    }

    private static class TrieNode {
        char data;
        Map<Character, TrieNode> childNodes;
        boolean isWord;

        public TrieNode(char data) {
            this.data = data;
            childNodes = new HashMap<>();
            isWord = false;
        }
    }

    public static void main(String[] args) {
        DynamicTrie trie = new DynamicTrie();
        trie.insert("aa");
        trie.insert("ccc");
        trie.insert("cae");
        trie.insert("ab");
        trie.insert("abc");
        trie.insert("ac");
        System.out.println(trie.exists("cae"));
    }
}
